import React, { PureComponent } from 'react'
import { connect } from 'dva'
import { Card, Tree, Icon, Modal, Input, Form, Spin } from 'antd';
import { OssUpload } from 'scd'
import { stringify } from 'qs';
import getFileId from '@/utils/getFileId';
import ModalForm from './ModalForm'

const { TreeNode } = Tree;
const Search = Input.Search;
const confirm = Modal.confirm;

const getParentKey = (id, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children && node.children.length !== 0) {
      if (node.children.some(item => item.id === id)) {
        parentKey = node.id
      } else if (getParentKey(id, node.children)) {
        parentKey = getParentKey(id, node.children);
      }
    }
  }
  if (parentKey) {
    parentKey = parentKey.toString();
  }
  return parentKey
};

@connect(({ loading, dispatch, app }) => ({
  reloading: loading.effects['app/getOrganizTree'],
  moloading: loading.effects['app/searchOrganizTree'],
  fileloading: loading.effects['app/getFileDownloadUrl'],
  addloading: loading.effects['app/addOrganizTree'],
  editloading: loading.effects['app/editOrganizTree'],
  app: app,
}))
@Form.create()


class OrganizationTree extends PureComponent {
  state = {
    loading: true,
    expandedKeys: [],
    searchValue: '',
    autoExpandParent: true,//自动展开父节点
    currentOrgId: "",
    //---------------------------------------------------------
    carteOrgVisible: false,//弹窗
    modalType: '',//弹窗类型
  }

  componentDidMount() {
    const { dispatch, app: { urlParams } } = this.props
    this.setState({
      expandedKeys: [urlParams]
    })
    dispatch({
      type: 'app/getOrganizTree',
      payload: { orgId: urlParams }
    })
    dispatch({
      type: 'app/getOrgcompanyList',
      payload: {
        orgId: urlParams
      }
    })
    new Promise((resolve) => {
      dispatch({
        type: 'app/searchOrganizTree',
        payload: {
          resolve,
          orgId: urlParams
        }
      })
    }).then((res) => {
      if (res.code === 1) {
        dispatch({
          type: 'app/getFileDownloadUrl',
          payload: [{
            fileInfoId: res.data.orgLogo,
            companyId: 1,
            moduleCode: "default",
            productLineId: 1,
            userId: 1
          }]
        })
      }
    })
  }

  onExpand = (expandedKeys) => {//组织树闭合开关
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }

  onChange = (e) => {//输入框change
    const { app: { organizaTreeList, organizaTreelistMap } } = this.props
    const value = e.target.value;
    const expandedKeys = organizaTreelistMap.map((item) => {
      if (item.name.indexOf(value) > -1) {
        return getParentKey(item.id, organizaTreeList);
      }
      return null;
    }).filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  }

  onSelect = (selectedKeys, info) => {//组织树选择
    const { dispatch } = this.props
    const { currentOrgId } = this.state
    if (selectedKeys[0]) {
      this.setState({
        currentOrgId: selectedKeys[0]
      })
    }
    // console.log(`payload--------->`, selectedKeys[0], currentOrgId)
    dispatch({
      type: 'orgInsider/getOrganizaInsider',
      payload: { orgId: selectedKeys[0] || currentOrgId }
    })
    dispatch({
      type: 'role/getRoleList',
      payload: {
        pageNum:1,
        pageSize:10,
        orgId: selectedKeys[0] || currentOrgId,
      }
    })
    dispatch({
      type: 'app/getOrgcompanyList',
      payload: { orgId: selectedKeys[0] || currentOrgId }
    })
    new Promise((resolve) => {
      dispatch({
        type: 'app/searchOrganizTree',
        payload: {
          resolve,
          orgId: selectedKeys[0] || currentOrgId
        }
      })
    }).then((res) => {
      if (res.code === 1) {
        dispatch({
          type: 'app/getFileDownloadUrl',
          payload: [{
            fileInfoId: res.data.orgLogo,
            companyId: 1,
            moduleCode: "default",
            productLineId: 1,
            userId: 1
          }]
        })
      }
    })
  }

  showCreateOrgForm = (e) => {//表单弹窗
    e.preventDefault();
    let type = e.currentTarget.getAttribute('data-type')
    let dataSource = JSON.parse(e.currentTarget.getAttribute('data-source'))
    // console.log(`show----------->`, type, dataSource)
    if (type === "delete") {
      this.setState({
        carteOrgVisible: false
      }, () => {
        this.showDeleteConfirm()
      })
      return
    }
    this.setState({
      modalType: type,
      organizationName: dataSource.name,
      carteOrgVisible: true,
    })
  }

  showDeleteConfirm = (data) => {//删除弹窗
    const { dispatch, app: { urlParams } } = this.props
    confirm({
      title: '确定要删除此组织吗?',
      content: '删除组织后改组织下的公司和部门、人员会xxx，你还要删除吗？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取 消',
      onOk() {
        new Promise((resolve) => {
          dispatch({
            type: 'app/deleteOrganizTree',
            payload: {
              resolve,
              organizationId: data.id
            }
          })
        }).then((code) => {
          if (code === 1) {
            dispatch({
              type: 'app/getOrganizTree',
              payload: {
                orgId: urlParams
              }
            })
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  handleOk = (e) => {//弹窗表单确认按钮
    e.preventDefault();
    const { modalType } = this.state
    const { form: { validateFieldsAndScroll, resetFields }, dispatch, app: { singleOriginal, urlParams }, addloading, editloading } = this.props
    validateFieldsAndScroll((error, value) => {
      if (error) return
      value.isOpen = value.isOpen ? 0 : 1
      value.orgState = value.orgState ? 0 : 1
      value.orgLogo = getFileId(value.orgLogo)
      // console.log('formValues======>', value, singleOriginal)
      if (modalType === 'add') {
        new Promise((resolve) => {
          dispatch({
            type: 'app/addOrganizTree',
            payload: {
              resolve,
              ...value,
              // topId: singleOriginal.topId,
              parentId: singleOriginal.id === 0 ? 1 : singleOriginal.id
            }
          })
        }).then((code) => {
          this.setState({ carteOrgVisible: false })
          if (code === 1) {
            dispatch({
              type: 'app/getOrganizTree',
              payload: {
                orgId: urlParams
              }
            })
          }
        })
      } else {
        new Promise((resolve) => {
          dispatch({
            type: 'app/editOrganizTree',
            payload: {
              resolve,
              ...value,
              id: singleOriginal.id,
              // topId: singleOriginal.topId,
              // parentId: singleOriginal.id === 0 ? 1 : singleOriginal.id
            }
          })
        }).then((code) => {
          this.setState({ carteOrgVisible: false })
          if (code === 1) {
            dispatch({
              type: 'app/getOrganizTree',
              payload: {
                orgId: urlParams
              }
            })
            new Promise((resolve) => {
              dispatch({
                type: 'app/searchOrganizTree',
                payload: {
                  resolve,
                  orgId: singleOriginal.id
                }
              })
            }).then((res) => {
              if (res.code === 1) {
                dispatch({
                  type: 'app/getFileDownloadUrl',
                  payload: [{
                    fileInfoId: res.data.orgLogo,
                    companyId: 1,
                    moduleCode: "default",
                    productLineId: 1,
                    userId: 1
                  }]
                })
              }
            })
          }
        })
      }
      resetFields();
    })
  }
  handleCancel = (e) => {//取消
    const { form: { resetFields } } = this.props
    this.setState({
      carteOrgVisible: false,
    });
    resetFields();
  }

  renderTree = (orgTree, orgProps) => {//组织树渲染
    const { searchValue } = this.state
    const { app: { urlParams } } = this.props
    return orgTree.map((item) => {
      if (!item.name) return
      const orgName = item.name
      const index = orgName.indexOf(searchValue);
      const beforeStr = item.name.substr(0, index);
      const afterStr = item.name.substr(index + searchValue.length);
      const name = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{ color: '#067dc6', fontWeight: 'bold' }}>{searchValue}</span>
          {afterStr}
          <Icon type="edit" data-type="edit" data-source={JSON.stringify(item)} onClick={this.showCreateOrgForm} style={{ cursor: 'pointer', marginLeft: '5px' }} />
          <Icon type="plus-circle" data-type="add" data-source={JSON.stringify(item)} onClick={this.showCreateOrgForm} style={{ cursor: 'pointer', marginLeft: '5px' }} />
          {item.topId === -1 ? "" : <Icon type="minus-circle" data-type="delete" data-source={JSON.stringify(item)} onClick={e => this.showDeleteConfirm(item)} style={{ cursor: 'pointer', marginLeft: '5px' }} />}
        </span>
      ) : <span>{item.name}</span>
      if (item.children && item.children.length !== 0) {
        return (
          <TreeNode key={item.id} title={name}>
            {this.renderTree(item.children)}
          </TreeNode>
        )
      }
      return <TreeNode key={item.id} title={name} />
    })
  }


  render() {
    const { searchValue, expandedKeys, autoExpandParent, orgTreeList,
      carteOrgVisible, modalType, organizationName,
    } = this.state;
    const { reloading, addloading, editloading, fileloading, app: { urlParams, organizaTreeList, imgUrlList }, form } = this.props


    return (
      <Card>{/* bordered={false} */}
        <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={this.onChange} />
        {organizaTreeList && organizaTreeList.length > 0 ?
          (<Tree
            showLine
            onExpand={this.onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onSelect={this.onSelect}>
            {this.renderTree(organizaTreeList)}
          </Tree>) : (<Spin
            size="small"
            spinning={reloading}
            tip="加载中..." />)}

        <Modal
          title={<span>
            {modalType === "add" ? "创建" : "编辑"}
            <span style={{ color: '#067dc6' }}>{organizationName}</span>
            {modalType === "add" ? "下的组织" : "的信息"}
          </span>}
          visible={carteOrgVisible}
          onOk={this.handleOk}
          confirmLoading={modalType === "add" ? !!addloading : !!editloading}
          onCancel={this.handleCancel}
        >
          <ModalForm form={form} modalType={modalType} />
        </Modal>

      </Card>
    );
  }
}

export default OrganizationTree;